package com.fourth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourth.entity.BankCard;
import com.fourth.entity.CardBinding;
import com.fourth.entity.User;
import com.fourth.mapper.AccountStatementMapper;
import com.fourth.mapper.CardBindingMapper;
import com.fourth.service.IBankCardService;
import com.fourth.service.ICardBindingService;
import com.fourth.service.IUserService;
import com.fourth.service.SmsService;
import com.fourth.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 银行卡表 服务实现类
 * </p>
 *
 * @author 邓建波
 * @since 2022-08-04
 */
@Service
public class CardBindingServiceImpl extends ServiceImpl<CardBindingMapper, CardBinding> implements ICardBindingService {

    @Autowired
    IBankCardService bankCardService;
    @Autowired
    IUserService userService;
    @Autowired
    SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CardBindingMapper cardBindingMapper;

    @Override
    public String getBankMsg(String cardId) {
        QueryWrapper<BankCard> wrapper = new QueryWrapper();
        wrapper.select("bank");
        wrapper.eq("card_id", cardId);
        BankCard bankCard = bankCardService.getBaseMapper().selectOne(wrapper);

        if (bankCard != null) {
            return bankCard.getBank();
        } else {
            return null;
        }
    }

    @Override
    public List<String> getPwd(String cardId, String userPhone) {
        //设置redis的key
        String redisKey = userPhone + ":validCode";
        //获取验证码
        String realCode = (String) redisTemplate.opsForValue().get(redisKey);
        //获取卡密和预留手机号
        QueryWrapper<BankCard> wrapper = new QueryWrapper();
        wrapper.eq("card_id", cardId);
        BankCard bankCard = bankCardService.getBaseMapper().selectOne(wrapper);

        //拼装返回对象
        ArrayList<String> returnList = new ArrayList<>();
        returnList.add(realCode);
        returnList.add(bankCard.getPhone());
        returnList.add(bankCard.getCardPassword());

        return returnList;
    }

    @Override
    public String getPwdName(String cardId) {
        return cardBindingMapper.getPwdName(cardId);
    }

    @Override
    public void sendValidCode(String userPhone) {
        //发送验证码到相应手机号
        String code = RandomUtil.randomNumbers(4);
        try {
            smsService.sendSms(userPhone, code);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //将验证码存储到redis中
        String redisKey = userPhone + ":validCode";
        redisTemplate.opsForValue().set(redisKey, code, 3000, TimeUnit.SECONDS);
    }


    @Override
    public int saveNewCard(String bank, String userPhone, String card) {
        // 通过用户手机号获取用户id
        final Long userId = UserHolder.getUser().getUserId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", userPhone);
        User user = userService.getBaseMapper().selectOne(wrapper);
        //查找用户表中是否存在该用户
        if (user == null) {
            return 3;
        }

        //查找用户是否对应
        if (!userId.equals(user.getUserId())) {
            return 2;
        }
        //查找是否已经绑定过
        QueryWrapper<CardBinding> cardWrapper = new QueryWrapper<>();
        cardWrapper.eq("card_id", card);
        CardBinding cardBinding1 = this.getBaseMapper().selectOne(cardWrapper);
        System.out.println(cardBinding1);
        //若已经绑定过则返回
        if (cardBinding1 != null) {
            return 1;
        }

        //验证通过，添加卡到用户下
        CardBinding cardBinding = new CardBinding();
        cardBinding.setCardId(card);
        cardBinding.setBank(bank);
        cardBinding.setUserId(user.getUserId());

        this.save(cardBinding);
        return 0;
    }

    @Override
    public int deleteCard(String card, String accountPassword) {
        Long userId = UserHolder.getUser().getUserId();
        String userPayPassword = userService.getById(userId).getUserPayPassword();

        //将银行卡纯数字部分提取
        String deleteCard = card.substring(0, card.lastIndexOf('(') - 1);

        if (!userPayPassword.equals(accountPassword)) {
            return 1;
        }

        //将该卡的绑定记录删除
        QueryWrapper<CardBinding> wrapper = new QueryWrapper<>();
        wrapper.eq("card_id", deleteCard);
        this.remove(wrapper);
        return 0;
    }
}
